package com.ygqh.baby.solr;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.model.ProductInfoForSolr;
import com.ygqh.baby.service.YgProductService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class ProductSolrApi extends SolrApi {
    private Logger mailLog = LoggerFactory.getLogger("mail");

    @Autowired
    private YgProductService ygProductService;

    public void updateProductSolr(Long productId) {
        ProductInfoForSolr infoForSolr = ygProductService.findProductForSolr(productId);
        if (infoForSolr != null) {
            this.addToSolr(infoForSolr);
        } else {
            this.delProduct(productId);
        }
    }

    public void updateProductSolr(List<Long> productIds) {
        if (CollectionUtils.isEmpty(productIds)) {
            return;
        }
        List<ProductInfoForSolr> listForSolr = ygProductService.findProductListForSolr(productIds);
        if (CollectionUtils.isEmpty(listForSolr)) {
            return;
        }
        this.addToSolr(listForSolr);

    }

    private void addToSolr(List<ProductInfoForSolr> addList) {
        if (CollectionUtils.isEmpty(addList)) {
            return;
        }

        try {
            addBatch(addList);
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
            mailLog.error("addToSolr error. productList = 【{}】", JSON.toJSONString(addList), e);
        }

    }

    private void addToSolr(ProductInfoForSolr product) {
        if (product == null) {
            return;
        }
        try {
            add(product);
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
            mailLog.error("addToSolr error. product = 【{}】", JSON.toJSONString(product), e);
        }
    }

    private void delProduct(Long productId) {
        if (productId == null) {
            return;
        }
        try {
            del(productId.toString());
        } catch (SolrServerException | IOException e) {
            mailLog.error("delProduct error. productId = 【{}】", productId, e);
            e.printStackTrace();
        }
    }

    private void delProduct(List<Long> productIds) {
        if (CollectionUtils.isEmpty(productIds)) {
            return;
        }
        String join = StringUtils.join(productIds, ",");
        String[] split = join.split(",");
        List<String> pIds = Arrays.asList(split);
        try {
            del(pIds);
        } catch (SolrServerException | IOException e) {
            mailLog.error("delProduct error. productId = 【{}】", join, e);
            e.printStackTrace();
        }
    }
}
